﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ZYHand.Service.Web.Test.Models;
using RabbitMQ.Client;
using ZYHand.Entity;
using  ZYHand.Utility;
using MongoDB.Driver;
using ZYHand.IService;
using ZYHand.DTO;

namespace ZYHand.Service.Web.Test.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        public IActionResult Push()
        {
            IRabbitMQService rabbitMQService = new RabbitMQService();

            PublishData<Order> publishData = new PublishData<Order>()
            {
                Type = EnumHelper.RabbitMQType.InsertOrder.ToString(),
                Data = new Order
                {
                    orderID = DateTime.Now.ToString("ddHHmmss"),
                    customerName = "tangzhiqiang,广东深圳，来自湖南，和老婆跟着小姨子"
                }
            };
            // rabbitMQService.Publish("Search", "SearchEx", "Search",JsonConvert.SerializeObject(new { ID=Convert.ToInt64(DateTime.Now.ToString("MMddHHmmss")),Name="tangzhiqiang"}));

            rabbitMQService.Publish("Search", "SearchEx", "Search", JsonConvert.SerializeObject(publishData));
          

            return new JsonResult(new { Status = 1001 });
        }

        public IActionResult Update(string orderID)
        {
            IRabbitMQService rabbitMQService = new RabbitMQService();

            PublishData<Order> publishData = new PublishData<Order>()
            {
                Type = EnumHelper.RabbitMQType.UpdateOrder.ToString(),
                Data = new Order
                {
                    orderID = orderID,
                    customerName = "liudahai,广东深圳，开发了小姨子"
                }
            };

            rabbitMQService.Publish("Search", "SearchEx", "Search", JsonConvert.SerializeObject(publishData));

            return new JsonResult(new { Status = 1001 });
        }


        public IActionResult Delete(string orderID)
        {
            IRabbitMQService rabbitMQService = new RabbitMQService();

            PublishData<Order> publishData = new PublishData<Order>()
            {
                Type = EnumHelper.RabbitMQType.DeleteOrder.ToString(),
                Data = new Order
                {
                    orderID = orderID,
                }
            };

            rabbitMQService.Publish("Search", "SearchEx", "Search", JsonConvert.SerializeObject(publishData));

            return new JsonResult(new { Status = 1001 });
        }


        [HttpGet]
        public IActionResult Pull(string wd, int pageindex = 1, int pagesize = 10)
        {
            var returnfield = "orderID,customerName,customerPhone,organizationID";
            var list = new List<FilterDefinition<MongoDBResponse>>();
            //查询字符串处理
            if (string.IsNullOrEmpty(wd))
                return null;
            else
            {
                string[] wdsWhile = wd.Split(' ');  //空白字符分隔
                string[] wdsDot = wd.Split(',');    //逗号字符分隔

                for (int i = 0; i < wdsDot.Length; i++)
                {
                    list.Add(Builders<MongoDBResponse>.Filter.Regex("orderID", "/" + wdsDot[i] + "/"));//查询条件2，可用于字符串模糊类型
                    list.Add(Builders<MongoDBResponse>.Filter.Regex("customerPhone", "/" + wdsDot[i] + "/"));//查询条件2，可用于字符串模糊类型,  //list.Add(Builders<MongoDBResponse>.Filter.Eq("Name", wdsDot[i]));//查询条件2，可用于字符串类型
                    list.Add(Builders<MongoDBResponse>.Filter.Regex("organizationID", "/" + wdsDot[i] + "/"));
                    list.Add(Builders<MongoDBResponse>.Filter.Regex("customerName", "/" + wdsDot[i] + "/"));
                }

                FilterDefinition<MongoDBResponse> filter = Builders<MongoDBResponse>.Filter.Or(list);   //多条件之前的逻辑运算：Or查询，And查询

                IMongoDBService mongoDBService = new MongoDBService();
                long count=0;//查询到的总条数
                var replaylist = mongoDBService.FindListByPage<MongoDBResponse>("Order", filter, pageindex, pagesize, out count, returnfield == null ? null : returnfield.Split(',')); //Order是集合(即关系数据库中的表名)，不需要提前创建

                SearchData<MongoDBResponse> searchData = new SearchData<MongoDBResponse>();
                searchData.Keywords = wd;
                searchData.Count = count;
                searchData.DataList = replaylist;
                searchData.From = pageindex;
                searchData.Size = pagesize;

                Console.WriteLine(count);

                return new JsonResult(searchData);
            }
        }
    }
}
